﻿package cn.poco.pepsi.activity.search;

import java.util.ArrayList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.provider.SearchRecentSuggestions;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import cn.poco.pepsi.R;
import cn.poco.pepsi.ResTabActivity;
import cn.poco.pepsi.TabTest;
import cn.poco.pepsi.activity.detail.ResDetailActivity;
import cn.poco.pepsi.activity.detail.ResDetailActivity_x;
import cn.poco.pepsi.adapter.SearchResultListAdapter;
import cn.poco.pepsi.bean.Area;
import cn.poco.pepsi.bean.Dish;
import cn.poco.pepsi.bean.Restaurant;
import cn.poco.pepsi.service.impl.SearchImpl;
import cn.poco.pepsi.util.Cons;
import cn.poco.pepsi.util.MyProgressDialog;
import cn.poco.pepsi.util.SearchSuggestionSampleProvider;

/**
 * 搜索结果页
 * 
 * @author tanglx
 * 
 */
public class SearchResultActivity extends Activity {
	private final static String TAG = "SearchResultActivity";
	private LinearLayout progress;
	private ProgressBar listFooterProgressbar;
	private TextView listFooterTextView;
	private Spinner spinner1, spinner2, spinner3;
	private ArrayList<Restaurant> list, list2;
	private ArrayList<Area> listArea;
	private ArrayList<Dish> listDish;
	private ListView listView;
	private Handler tHandler;
	private String cityCode, cityName, titleName;
	private ProgressDialog dialog;
	private SearchResultListAdapter searchListAdapter;
	private TextView titleTextView;
	private Button backBtn;
	// 搜索条件
	private String key;
	private String areaId;
	private String dish;
	private String locationId; // 无用
	private String dishId;
	private boolean ispepsi=false;
	private String ispepsiFlag="no";
	private String mesg="nothing";
	// 筛选条件
	private String dis;
	private String vouch;
	// 起始结果
	private int s;
	private String l;

	private SearchImpl searchImpl;
	private boolean isClick, isClickFooter;
	private OnItemSelectedListener spinnerItemSelectedListener1, spinnerItemSelectedListener2,
			spinnerItemSelectedListener3;
	private String tempTitleArea = null, tempTitleDish = null, tempCondition = null;
	// 更多
	LinearLayout viewMore;

	// 错误处理
	private LinearLayout error;
	private Button tautology;
	private Button setBtn;

	// 无数据处理
	private TextView noDataTextView;

	public void initView() {
		isClick = false;
		isClickFooter = false;

		titleTextView = (TextView) findViewById(R.id.show_title);
		titleTextView.setText("搜索结果");
		backBtn = (Button) findViewById(R.id.top_left_btn);
		// 处理错误信息
		error = (LinearLayout) findViewById(R.id.error);
		error.setVisibility(View.GONE);
		tautology = (Button) findViewById(R.id.tautology);
		setBtn = (Button) findViewById(R.id.setnet);
		noDataTextView = (TextView) findViewById(R.id.ErrorMessage);

		progress = (LinearLayout) findViewById(R.id.progressbar);
		spinner1 = (Spinner) findViewById(R.id.area_spinner);
		spinner2 = (Spinner) findViewById(R.id.dish_spinner);
		spinner3 = (Spinner) findViewById(R.id.sort_spinner);
		listView = (ListView) findViewById(R.id.listview);
		listView.setDivider(null);
		listView.setDividerHeight(0);

		// 处理传递过来的值  用于标题显示
		titleName = getIntent().getExtras().getString(Cons.ACTIVITY_TOP_TITLE);
		if (titleName != null) {
			setTitle(titleName);
			titleName = "";
		}
		
		key=getIntent().getExtras().getString(Cons.HOT_SEARCH_KEYWORD);
		ispepsiFlag=getIntent().getExtras().getString(Cons.ISPEPSI_RES);
		
		if(ispepsiFlag.equals("#ispepsi_poco_xw#")){
			ispepsi=true;
		}else{
			ispepsi=false;
		}
		
		try{
			mesg=getIntent().getExtras().getString("MES");
		}catch(Exception e){
			mesg="nothing";
		}
		
		
		

		cityName = getIntent().getExtras().getString(Cons.CITY_NAME);//获取城市名
		locationId = getIntent().getExtras().getString(Cons.CIRCLE_CODE);//获取城市周边 代码
		areaId = getIntent().getExtras().getString(Cons.AREA_CODE);//获取城市区域
		if (locationId != null) {
			//如果 周边代码不为空  －－－－－>周边值 赋给 区域值
			areaId = locationId;
			locationId = null;
		}

		//获取菜式
		dishId = String.valueOf(getIntent().getExtras().getLong(Cons.SEARCH_DISHID));
		if (dishId.equals("0")) {
			dishId = null;
		}

		
		//  从全局中获取城市代码
		SharedPreferences sharedPreferences = getSharedPreferences(Cons.GPS_CITY_CODE, MODE_PRIVATE);
		cityCode = sharedPreferences.getString(Cons.CITY_CODE, "000000");
		
		//设置获取十条信息
		s = 0;
		l = "10";

		searchImpl = new SearchImpl(this);
		
		//************************* 城市区域 下拉列表  *******************************
		try {
		//根据城市代码获取城市区域 列表
			listArea = searchImpl.getArea(cityCode, this);
			String[] temp = new String[listArea.size() + 1];//将城市区域 列表变成新一数组  首位加入 "全部区域"
			temp[0] = "全部区域";
			for (int j = 0; j < listArea.size(); j++) {
				temp[j + 1] = listArea.get(j).getName();
			}
			
			//填充区域下拉列表
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner, temp);
			adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spinner1.setAdapter(adapter);
			
		} catch (Exception e) {
			e.printStackTrace();
			//如果有异常，handler发出错误信号
			handler.sendEmptyMessage(Cons.CONN_ERROR);
		}
//********************************  菜式 下拉列表    *******************************
		try {
			listDish = searchImpl.getDishs(cityCode, "dish", this);
			String[] temp1 = new String[listDish.size() + 1];
			temp1[0] = "全部菜式";
			for (int j = 0; j < listDish.size(); j++) {
				temp1[j + 1] = listDish.get(j).getName();
			}
			ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, R.layout.spinner, temp1);
			adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spinner2.setAdapter(adapter2);

		} catch (Exception e) {
			e.printStackTrace();
			handler.sendEmptyMessage(Cons.CONN_ERROR);
		}
//*********************************         *************************
		try {
			// 食评数和加盟两个条件 接口没有
			String[] temp1 = new String[] { "不限条件", "出品", "服务", "人均", "加盟" };
			ArrayAdapter<String> adapter3 = new ArrayAdapter<String>(this, R.layout.spinner, temp1);
			adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spinner3.setAdapter(adapter3);
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 最低部更多的视图
		viewMore = (LinearLayout) LayoutInflater.from(SearchResultActivity.this).inflate(R.layout.list_footer, null);
		listFooterProgressbar = (ProgressBar) viewMore.findViewById(R.id.list_footer_progress);
		listFooterTextView = (TextView) viewMore.findViewById(R.id.list_footer_text);
	}

	// 接收全局搜索字符串数据（从启动 搜索结果ACT  的ACT获取）
	private void doSearchQuery() {
		final Intent intent = getIntent();
		String query = intent.getStringExtra(SearchManager.QUERY);
		
		// 保存搜索记录
		if (query != null) {
			SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
					SearchSuggestionSampleProvider.AUTHORITY, SearchSuggestionSampleProvider.MODE);
			suggestions.saveRecentQuery(query, null);
			/*if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
				key = query;
				setTitle(key);
			}*/
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_result);
		doSearchQuery();
		initView();

		// 首次进入加载搜索结果数据
		HandlerThread handlerThread = new HandlerThread(TAG);
		handlerThread.start();
		tHandler = new Handler(handlerThread.getLooper());
		tHandler.post(runnable);

		
		//加载失败后出现的网络设置按钮
		setBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
				startActivity(intent);
			}
		});

		
		
		tautology.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				spinner1.setClickable(true);//可点击
				spinner2.setClickable(true);
				spinner3.setClickable(true);
				progress.setVisibility(View.VISIBLE);
				error.setVisibility(View.GONE);
				tHandler.post(runnable);//重新加载
			}
		});

		
		//全部地区列表 监听事处
		spinnerItemSelectedListener1 = new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				System.out.println("is spinner 1");
				if (isClick) {
					isClickFooter = true;
					if (position == 0) {
						areaId = null;
						tempTitleArea = "全部地区";
					} else {
						areaId = listArea.get(position - 1).getKey();
						tempTitleArea = listArea.get(position - 1).getName();
					}
					setMyTitle();

				}

			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
			}
		};

		spinnerItemSelectedListener2 = new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				System.out.println("is spinner 2");
				tempTitleDish = null;
				if (isClick) {
					isClickFooter = true;
					if (position == 0) {
						dishId = null;
						tempTitleDish = "全部菜式";
					} else {
						dishId = String.valueOf(listDish.get(position - 1).getId());
						tempTitleDish = listDish.get(position - 1).getName();
					}
					setMyTitle();
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}
		};

		spinnerItemSelectedListener3 = new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				if (isClick) {
					isClickFooter = true;
					switch (position) {
					case 0:
						dis = null;
						tempCondition = "默认排序";
						break;
					case 1:
						dis = "0";
						tempCondition = "按出品排序";
						break;
					case 2:
						dis = "1";
						tempCondition = "按服务排序";
						break;
					case 3:
						dis = "2";
						tempCondition = "按人均排序";
						break;
					case 4:
						dis = "3";
						tempCondition = "按是否有加盟餐厅排序";
						break;
					default:
						break;
					}
					setMyTitle();
				}

			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}
		};

		spinner1.setOnItemSelectedListener(spinnerItemSelectedListener1);
		spinner2.setOnItemSelectedListener(spinnerItemSelectedListener2);
		spinner3.setOnItemSelectedListener(spinnerItemSelectedListener3);
		
		
		
     //结果列表事件监听
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				int count = listView.getCount();
				if (arg2 == count - 1) {
					//点击最后一项（更多）
					isClickFooter = true;
					s = s + 10;
					tHandler.post(runnablere);
					listFooterProgressbar.setVisibility(View.VISIBLE);
					listFooterTextView.setText("加载中...");
				} else {
					//点击具体一项
					Restaurant restaurant = (Restaurant) arg0.getItemAtPosition(arg2);
					//向ResTabActivity.class发送餐厅信息：餐厅对象，餐厅代码
					Intent intent = new Intent(SearchResultActivity.this,ResTabActivity.class);
					intent.putExtra(Cons.RESDATA, restaurant);
					intent.putExtra(Cons.RES_CODE,
					 String.valueOf(list.get(arg2).getId()));
					startActivity(intent);
				}

			}
		});

		
		//返回按钮
		backBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	//设置标题
	public void setMyTitle() {
		Boolean flag = false;
		if (tempTitleArea == null) {
			tempTitleArea = "";
		}
		if (tempTitleDish == null) {
			flag = true;
		}
		if (tempCondition == null) {
			tempCondition = "";
		}
		if (flag) {
			setTitle((tempTitleArea + " " + tempCondition));
		} else {
			setTitle((" " + tempTitleArea + " " + tempTitleDish + " " + tempCondition));

		}
		dialog = MyProgressDialog.show(SearchResultActivity.this, "正在加载，请稍后...");
		tHandler.post(runnable);//重新加载
	}
	
	
	
//根据handler发出的信号进行相应的操作
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				isClick = true;
				spinner1.setClickable(true);
				spinner2.setClickable(true);
				spinner3.setClickable(true);

				if (dialog != null) {
					dialog.dismiss();
				}

				// 筛选条件没有数据
				if (list.size() > 0) {
					searchListAdapter = new SearchResultListAdapter(SearchResultActivity.this, list, handler);
					// 仅在第一次加载的时候添加更多的尾部
					if (!isClickFooter && list.size() >= 10) {
						listView.addFooterView(viewMore);
					}
					listView.setAdapter(searchListAdapter);
					progress.setVisibility(View.GONE);
					listView.setVisibility(View.VISIBLE);
				} else {
					handler.sendEmptyMessage(3);
				}
				break;
			case 2:
				if (list2.size() < 10) {
					listView.removeFooterView(viewMore);
				} else {
					list.addAll(list2);
					listFooterProgressbar.setVisibility(View.GONE);
					listFooterTextView.setText("更多");
					listFooterTextView.setTextColor(Color.RED);
				}
				searchListAdapter.notifyDataSetChanged();
				break;

			// 筛选得不到任何数据
			case 3:
				listView.setVisibility(View.GONE);
				noDataTextView.setVisibility(View.VISIBLE);
				break;

			// 连接错误
			case Cons.CONN_ERROR:
				spinner1.setClickable(false);
				spinner2.setClickable(false);
				spinner3.setClickable(false);
				if (dialog != null) {
					dialog.dismiss();
				}
				progress.setVisibility(View.GONE);
				listView.setVisibility(View.GONE);
				error.setVisibility(View.VISIBLE);
				break;
			default:
				break;
			}
		}
	};

	Runnable runnable = new Runnable() {
		@Override
		public void run() {
			try {
				list = searchImpl
						.getFilterRestaurant(key, areaId, dish, cityCode, s, l, dis, vouch, locationId, dishId,ispepsi,mesg);
				if (list != null) {
					handler.sendEmptyMessage(1);
				}
			} catch (Exception e) {
				e.printStackTrace();
				handler.sendEmptyMessage(Cons.CONN_ERROR);
			}
		}
	};

	Runnable runnablere = new Runnable() {
		@Override
		public void run() {
			try {
				list2 = searchImpl.getFilterRestaurant(key, areaId, dish, cityCode, s, l, dis, vouch, locationId,
						dishId,ispepsi,mesg);
				if (list2 != null) {
					handler.sendEmptyMessage(2);
				}
			} catch (Exception e) {
				e.printStackTrace();
				handler.sendEmptyMessage(Cons.CONN_ERROR);
			}
		}
	};

}
